<script setup lang="ts">
/*导入socket.ic插件*/
import { io } from "socket.io-client";
import { nextTick, onBeforeUnmount, onMounted, Ref, ref } from "vue";
import { storeToRefs } from "pinia";
import type { RouteLocationNormalized } from "vue-router";
import { useRoute } from "vue-router";
import { baseURL } from "@/utils/request.ts";
import { getUserInfo } from "@/utils/localStorage.ts";
import type { UserInfo } from "@/types/userTypes/userTypes.ts";
import type { Socket } from "socket.io-client";
import type { Message, TimeMessages } from "@/types/chitchatTypes/chitchatTypes.ts";
import { MsgType } from "@/enums";
import { Image, OrderType } from "@/types/consultTypes/consultTypes.ts";
import RoomStatus from "@/views/home/views/chitchat/components/roomStatus.vue";
import RoomMessage from "@/views/home/views/chitchat/components/roomMessage.vue";
import RoomAction from "@/views/home/views/chitchat/components/roomAction.vue";
import useUserStore from "@/pinia/modules/userStore/userStore.ts";
import useConsultStore from "@/pinia/modules/consultStore/consultStore.ts";


const route: RouteLocationNormalized = useRoute();
const userStore = useUserStore();
const consultStore = useConsultStore();

const { orderDetail } = storeToRefs(consultStore);

/*
* 导入socket.ic插件
* 初始化创建wx长连接(打电话)
* 1.通过io函数传入后台ws链接地址和相关参数
* 2.连接建立成功后的相关事件
*  -通过io实例的connect事件，监听连接是否成功
*  -通过io实例的error事件，监听连接是否错误
*  -通过io实例的disconnect事件，监听连接断开
* */

/*socket实例*/
let socket: Socket;
/*聊天列表*/
const messageList: Ref<Message[]> = ref<Message[]>([]);
/*初始化socket的函数*/
const initSocket = () => {
   socket = io(baseURL, {
      auth: {
         token: `Bearer ${getUserInfo<UserInfo>().token}`,
      },
      query: {
         orderId: route.query.orderId,
      },
   });
   socket.on("connect", () => {
      console.log("socket连接成功");
   });
   socket.on("error", () => {
      console.log("socket连接失败");
   });
   socket.on("disconnect", () => {
      console.log("socket断开连接");
   });

   // 接收wx服务器给浏览器发送的默认数据
   socket.on("chatMsgList", ({ data }: { data: TimeMessages[] }) => {
      const result: Message[] = [];
      data.forEach((item) => {
         result.push({ id: item.createTime, msgType: MsgType.Notify, msg: { content: item.createTime } } as Message);
         result.push(...item.items);
      });
      messageList.value.push(...result);
   });

   // 接收医生消息
   socket.on("receiveChatMsg", async (event) => {
      messageList.value.push(event);
      await nextTick();
      window.scrollTo(0, document.body.scrollHeight);
   });

   //接收订单变化的消息
   socket.on("statusChange", () => {
      // 发送请求重新获取订单详情
      consultStore.fetchConsultOrderDetail(route.query.orderId as string);
      console.log("订单更新了");
   });

};


const getText = (text: string) => {
   socket.emit("sendChatMsg", {
      from: userStore.userInfo?.id,
      to: consultStore.orderDetail.docInfo?.id,
      msgType: MsgType.MsgText,
      msg: { content: text },
   });
};


const getImg = (img: Image) => {
   socket.emit("sendChatMsg", {
      from: userStore.userInfo?.id,
      to: orderDetail.value?.docInfo?.id,
      msgType: MsgType.MsgImage,
      msg: { picture: img },
   });
};

onMounted(() => {
   // 初始化socket
   initSocket();


});
onMounted(() => {
   // 发送请求获取订单详情
   consultStore.fetchConsultOrderDetail(route.query.orderId as string);
});

onBeforeUnmount(() => {
   // 关闭socket
   socket.close();
});

</script>

<template>
   <div class="room-page">
      <RoomStatus :status="orderDetail.status" :countdown="orderDetail.countdown"></RoomStatus>
      <RoomMessage :list="messageList"></RoomMessage>
      <RoomAction :disabled="orderDetail?.status !== OrderType.ConsultChat" @sendText="getText" @sendImg="getImg"></RoomAction>
   </div>
</template>

<style lang="scss" scoped>
.room-page {
   padding-bottom: 60px;
   min-height: 100vh;
   box-sizing: border-box;
   background-color: var(--cp-bg);

   .van-pull-refresh {
      width: 100%;
      min-height: calc(100vh - 150px);
   }
}
</style>
